package com.study.hot.jetpack.room.test_address

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import com.study.hot.R
import com.study.hot.jetpack.room.test_address.repository.AddressRepository
import com.study.hot.jetpack.room.test_address.viewmodel.AddressViewModel
import kotlinx.android.synthetic.main.address_fragment.*
import org.jetbrains.anko.sdk27.coroutines.onClick

class AddressFragment : Fragment() {

    companion object {
        fun newInstance() = AddressFragment()
    }

    private lateinit var viewModel: AddressViewModel
    private lateinit var mRootView: View

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        mRootView = inflater.inflate(R.layout.address_fragment, container, false)
        return mRootView
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProvider(this).get(AddressViewModel::class.java)
        val navController = Navigation.findNavController(mRootView)
        addAddressBtn.onClick {
            navController.navigate(R.id.action_addressFragment_to_addAdressFragment)
        }

        queryAddressBtn.onClick {
            //查询
            val addressList = AddressRepository.newInstance(requireContext()).addressDao.getAddress()
            val sb = StringBuilder()
            addressList.forEach {
                sb.append(it).append("\n")
            }
            addressListTv.text = sb.toString()
        }

        delAddressBtn.onClick {
            AddressRepository.newInstance(requireContext()).addressDao.deleteAll()
        }

    }

}
